package service

import (
	"github.com/golang/protobuf/proto"
	"leaf/common"
	. "leaf/core/error"
	"leaf/core/service"
	"leaf/core/service/timer"
	"leaf/core/tool"
	"sync"
	"sync/atomic"
	//. "github.com/name5566/core/tool"
	"leaf/pb"
)

var POOL_MAP = map[int32]int32{
	1: 1,
}

var msid int32

type MatchPool struct {
	sync.Mutex
	flag  int32
	Pool  map[uint64]*pb.MatchData
	Queue []*pb.MatchData
}

func (p *MatchPool) PoolLock() bool {
	return atomic.CompareAndSwapInt32(&p.flag, 0, 1)
}

func (p *MatchPool) PoolUnLock() bool {
	return atomic.CompareAndSwapInt32(&p.flag, 1, 0)
}

type MatchService struct {
	*service.Service
	pool  map[int32]*MatchPool
	timer *timer.Timer
	sid   int32
}

func NewMatchService(name string) *MatchService {
	s := &MatchService{
		Service: service.NewService(1),
		pool:    map[int32]*MatchPool{},
	}

	return s
}

func (s *MatchService) OnInit() {
	for _, pt := range POOL_MAP {
		s.pool[pt] = &MatchPool{
			Pool:  map[uint64]*pb.MatchData{},
			Queue: make([]*pb.MatchData, 0, 1024),
		}
	}

	s.sid = atomic.AddInt32(&msid, 1)
}

// 每秒执行
func (s *MatchService) Timer() {
	for _, data := range s.pool {
		if !data.PoolLock() {
			continue
		}

		data.Lock()
		for _, v := range data.Queue {
			data.Pool[v.User.GetUserid()] = v
		}
		data.Queue = data.Queue[0:0]
		data.Unlock()

		if len(data.Pool) < 4 {
			continue
		}

		var list []*pb.DbUser
		for _, v := range data.Pool {
			list = append(list, v.User)
			if len(list) == 4 {
				break
			}
		}

		if len(list) > 0 {
			for _, u := range list {
				delete(data.Pool, u.GetUserid())

				common.SendMsg(u.GetLsid(), u.GetUserid(), &pb.S2C_TestNotfiy{
					Data: proto.String("test notify~"),
				})
			}
		}

		data.PoolUnLock()
	}
}

func (s *MatchService) StartMatch(pt int32, user *pb.DbUser) *Error {
	var pool, _ = s.pool[pt]
	if pool == nil {
		return Error_DBErr
	}

	pool.Lock()
	defer pool.Unlock()

	pool.Queue = append(pool.Queue, &pb.MatchData{
		User:  user,
		Mtime: proto.Int64(tool.UnixSec()),
	})

	return nil
}
